package org.common.listener;

import org.apache.commons.lang3.StringUtils;
import org.common.exception.DtsException;
import org.common.model.BaseEntity;
import org.common.model.vo.TokenInfoVO;
import org.common.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.persistence.PreUpdate;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;


@Component
public class BaseEntityListener {

    @PreUpdate
    public void preUpdate(BaseEntity entity) {

        if (entity != null) {
            entity.setLastUpdateDate(new Date());
            entity.setLastUpdateUserId(currentUser());
        }
    }

    public String currentUser() {
        HttpServletRequest request = request();
        String token = this.request().getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
        if(StringUtils.isBlank(token)){
            throw new DtsException(201,"201","token不存在");
        }
        TokenInfoVO tokenInfoVo = JwtUtils.decodeJwt(token);
        return tokenInfoVo.getUserId();
    }

    public HttpServletRequest request() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        assert requestAttributes != null;

        return requestAttributes.getRequest();
    }
}
